<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="50%"
    @close="cancel"
    :close-on-click-modal="false"
  >
    <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" :disabled="!!form.id" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入昵称" maxlength="30" />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select
          v-model="form.deptId"
          :data="deptOptions"
          :props="{ value: 'id', label: 'name', children: 'children' }"
          value-key="id"
          placeholder="请选择所属部门"
          check-strictly
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="关联角色" prop="roleIds">
        <el-select
          v-model="form.roleIds"
          multiple
          collapse-tags
          :max-collapse-tags="2"
          placeholder="请选择关联角色"
          style="width: 240px"
          clearable
        >
          <el-option
            v-for="role in roleOptions"
            :key="role.id"
            :label="role.roleName"
            :value="role.id"
            :disabled="role.disabled"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" placeholder="请输入手机号" maxlength="11" />
      </el-form-item>
      <el-form-item label="账户密码" prop="password" v-if="false">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入账户密码,如果不输入默认dc@123456+"
          show-password
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
          maxlength="200"
          show-word-limit
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { listDept } from '@/api/dept'
import { listRole } from '@/api/roles'
import { addUser, updateUser, getUser } from '@/api/user'

// 接口定义
interface RoleOption {
  id: number
  roleName: string
  roleKey?: string
  status?: string | number
  disabled?: boolean
}

interface UserForm {
  id?: number
  username: string
  nickname: string
  deptId: number | null
  gender: number
  roleIds: number[]
  mobile: string
  password?: string
  status: number
  remark: string
}

const emit = defineEmits(['success'])

// 表单ref
const userFormRef = ref<FormInstance>()
// 显示状态
const dialogVisible = ref(false)
// 标题
const title = ref('新增用户')
// 提交状态
const submitLoading = ref(false)
// 部门树选项
const deptOptions = ref([])
// 角色选项
const roleOptions = ref<RoleOption[]>([])

// 表单校验规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  deptId: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  roleIds: [
    { required: true, type: 'array', message: '请选择关联角色', trigger: 'change' }
  ],
  password: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
})

/** 获取部门树选项 */
const getDeptTree = async () => {
  try {
    const res = await listDept()
    //添加顶级部门
    const topDept = {
      id: 1,
      name: '北京东圣'
    }
    res.data.unshift(topDept)
    deptOptions.value = res.data
  } catch (error: any) {
    ElMessage.error(error.msg || '获取部门列表失败')
  }
}

/** 获取角色选项 */
const getRoleOptions = async () => {
  try {
    const res = await listRole()
    roleOptions.value = res.data.list.map(role => ({
      id: role.id,
      roleName: role.name,
      disabled: role.status === 0
    }))
  } catch (error: any) {
    ElMessage.error(error.msg || '获取角色列表失败')
  }
}

// 初始表单数据
const initialForm: UserForm = {
  username: '',
  nickname: '',
  deptId: null,
  gender: 1,
  roleIds: [],
  mobile: '',
  password: '',
  status: 1,
  remark: '',
}

// 表单数据
const form = reactive<UserForm>({...initialForm})

/** 表单重置 */
const reset = () => {
  // 重要：使用一个新的空对象来存储初始值
  const resetForm = { ...initialForm }
  // 清空所有现有属性
  Object.keys(form).forEach(key => {
    delete form[key]
  })
  // 重新赋值初始属性
  Object.assign(form, resetForm)
  // 重置表单验证状态
  nextTick(() => {
    userFormRef.value?.clearValidate()
  })
}

/** 取消按钮 */
const cancel = () => {
  reset()
  dialogVisible.value = false
}

/** 新增/修改操作 */
const submitForm = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        const data = { ...form }
        if (form.id) {
          delete data.password
          await updateUser(data)
          ElMessage.success('修改成功')
        } else {
          if (!data.password) {
            data.password = 'dc@123456+' // 默认密码
          }
          await addUser(data)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        emit('success')
      } catch (error: any) {
        ElMessage.error(error.msg || '操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

/** 显示弹框 */
const show = async (row?: Partial<UserForm>) => {
  // 先重置表单
  reset()

  try {
    // 加载选项数据
    await Promise.all([getDeptTree(), getRoleOptions()])

    if (row?.id) {
      const res = await getUser(row.id)
      // 确保角色ID是数组格式
      const userData = {
        ...res.data,
        roleIds: Array.isArray(res.data.roleIds) ? res.data.roleIds : []
      }
      Object.assign(form, userData)
      title.value = '修改用户'
    } else {
      // 新增时确保表单是完全干净的
      title.value = '新增用户'
    }

    dialogVisible.value = true
  } catch (error: any) {
    ElMessage.error(error.msg || '获取数据失败')
  }
}

defineExpose({
  show
})
</script>

<style scoped>
.dialog-footer {
  padding: 20px 0 0;
}
</style>